package com.yx.frame.builder;

import java.io.File;
import java.io.FileFilter;
import java.util.List;

import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Tree;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.eclipse.wb.swt.SWTResourceManager;
import com.yx.frame.builder.validate.ServiceBuilderConfigManager;
import org.eclipse.swt.widgets.Table;

public class LeftControlTree extends Composite {

	static Shell window = null;
	public static String ROOT_PATH = null;
	private Tree fileListTree;
	
	Image home = SWTResourceManager.getImage(LeftControlTree.class,
			"/com/yx/frame/builder/image/home.png");	
	Image fileImage = SWTResourceManager.getImage(LeftControlTree.class,
			"/com/yx/frame/builder/image/file.png");
	TreeItem selectedItem;
	Button addButton;
	Button deleteButton;
	LeftControlTree leftControlTree;
	private Button bValigator;
	Button bCodeCompile;
	Button refreshButton;
	private Table fileMethodList;

	/**
	 * Create the composite.
	 * 
	 * @param parent
	 * @param style
	 */
	public LeftControlTree(Composite parent, int style) {
		super(parent, style);
		window = (Shell) parent;
		leftControlTree = this;
		Button button = new Button(this, SWT.NONE);
		button.setToolTipText("选择工程的src目录");
		// button.setImage(SWTResourceManager.getImage(LeftControlTree.class,
		// "/com/yx/frame/builder/image/home.png"));
		button.setText("打开");
		button.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				DirectoryDialog folderdlg = new DirectoryDialog(window);
				folderdlg.setText("工作空间选择");
				folderdlg.setFilterPath("./");
				folderdlg.setMessage("请选择相应的工作空间");
				String selecteddir = folderdlg.open();
				if (selecteddir == null) {
					return;
				}
				ROOT_PATH = selecteddir;
				bValigator.setEnabled(true);
				bCodeCompile.setEnabled(true);
				refreshButton.setEnabled(true);

				refrashTree();
				window.getChildren()[1].setVisible(false);
			}
		});
		button.setBounds(0, 0, 47, 27);

		addButton = new Button(this, SWT.NONE);
		addButton.setEnabled(false);
		addButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if (selectedItem == null) {
					MessageBox messageBox = new MessageBox(window, SWT.OK);
					messageBox.setMessage("请选择操作的路径!");
					if (messageBox.open() == SWT.OK) {
						return;
					} else {
						return;
					}
				}

				String type = (String) selectedItem.getData("Type");
				if ("WorkSpace".equals(type)) {
					AddFileDialog addFileDialog = new AddFileDialog(window,
							SWT.NONE, leftControlTree);
					addFileDialog.open();
				}
				window.getChildren()[1].setVisible(false);
			}
		});
		addButton.setBounds(173, 0, 47, 27);
		addButton.setText("添加");

		deleteButton = new Button(this, SWT.NONE);
		deleteButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if (selectedItem == null) {
					MessageBox messageBox = new MessageBox(window, SWT.OK);
					messageBox.setMessage("请选择操作的路径!");
					if (messageBox.open() == SWT.OK) {
						return;
					} else {
						return;
					}
				}
				String type = (String) selectedItem.getData("Type");
				if ("File".equals(type)) {
					String path = (String) selectedItem.getData("Path");
					MessageBox messageBox = new MessageBox(window, SWT.OK
							| SWT.CANCEL);
					messageBox.setMessage("您确定要删除文件：" + path + "吗?");
					if (messageBox.open() == SWT.OK) {
						File f = new File(path);
						f.delete();
						refrashTree();
						window.getChildren()[1].setVisible(false);
						return;
					}
				}
			}
		});
		deleteButton.setEnabled(false);
		deleteButton.setText("删除");
		deleteButton.setBounds(224, 0, 47, 27);

		refreshButton = new Button(this, SWT.NONE);
		refreshButton.setEnabled(false);
		refreshButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				refrashTree();
				window.getChildren()[1].setVisible(false);
			}
		});
		refreshButton.setText("刷新");
		refreshButton.setBounds(276, 0, 47, 27);

		fileListTree = new Tree(this, SWT.BORDER);
		fileListTree.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				try {
					selectedItem = ((Tree) e.getSource()).getSelection()[0];
					String type = (String) selectedItem.getData("Type");
					if ("WorkSpace".equals(type)) {
						addButton.setEnabled(true);
						deleteButton.setEnabled(false);
						window.getChildren()[1].setVisible(false);
						refrashMethodTable(null,null);
					} else if ("File".equals(type)) {
						addButton.setEnabled(false);
						deleteButton.setEnabled(true);
						String path = (String) selectedItem.getData("Path");
						MethodPublic methodPublic = (MethodPublic) window
								.getChildren()[1];
						methodPublic.editMethod(path, null);
						methodPublic.setVisible(true);
						refrashMethodTable(path,null);
					} 
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		});
		fileListTree.setBounds(0, 28, 324, 345);

		bCodeCompile = new Button(this, SWT.NONE);
		bCodeCompile.setToolTipText("编译生成java代码");
		bCodeCompile.setEnabled(false);
		bCodeCompile.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				window.getChildren()[1].setVisible(false);
				CodeBuildDialog codeBuildDialog = new CodeBuildDialog(window,
						SWT.NONE);
				codeBuildDialog.open();
			}
		});
		bCodeCompile.setText("编译");
		bCodeCompile.setBounds(52, 0, 47, 27);

		bValigator = new Button(this, SWT.NONE);
		bValigator.setEnabled(false);
		bValigator.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				ValidatorRegister validatorRegister = new ValidatorRegister(
						window, SWT.NONE);
				validatorRegister.open();
			}
		});
		bValigator.setText("设置");
		bValigator.setBounds(105, 0, 47, 27);

		fileMethodList = new Table(this, SWT.BORDER | SWT.FULL_SELECTION);
		fileMethodList.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				int sIdx = fileMethodList.getSelectionIndex();
				if (sIdx >= 0) {
					try {
						TableItem item = fileMethodList.getItem(sIdx);
						addButton.setEnabled(false);
						deleteButton.setEnabled(false);
						String path = (String) item.getData("Path");
						String mathodName = (String) item.getText(1);
						MethodPublic methodPublic = (MethodPublic) window
								.getChildren()[1];
						methodPublic.editMethod(path, mathodName);
						methodPublic.setVisible(true);
					} catch (Exception ex) {
					}
				}
			}
		});
		
		fileMethodList.setBounds(0, 374, 323, 207);
		fileMethodList.setHeaderVisible(true);
		fileMethodList.setLinesVisible(true);
		TableColumn tc1 = new TableColumn(fileMethodList, SWT.CENTER);
		TableColumn tc2 = new TableColumn(fileMethodList, SWT.LEFT);
		// TableColumn tc3 = new TableColumn(fileMethodList, SWT.LEFT);
		TableColumn tc4 = new TableColumn(fileMethodList, SWT.LEFT);

		tc1.setText("ID");
		tc2.setText("方法名");
		// tc3.setText("类型");
		tc4.setText("说明");
		tc1.setWidth(30);
		tc2.setWidth(110);
		// tc3.setWidth(55);
		tc4.setWidth(160);

	}

	public void refrashTree() {
		if (ROOT_PATH == null)
			return;
		ServiceBuilderConfigManager.getInstance().refrashValidators(
				ROOT_PATH + "/builder/ServiceBuilder.conf");
		File root = new File(ROOT_PATH);
		fileListTree.removeAll();
		selectedItem = null;
		TreeItem rootItem = new TreeItem(fileListTree, 0);
		rootItem.setText(ROOT_PATH);
		rootItem.setImage(home);
		rootItem.setData("Type", "WorkSpace");
		rootItem.setData("Path", this.ROOT_PATH);
		searchDirectory(root, rootItem);
		refrashMethodTable(null,null);
	}

	private void searchDirectory(File file, TreeItem rootItem) {
		if (file.isDirectory()) {
			File[] files = file.listFiles(new xmlFilter());
			for (int i = 0; i < files.length; i++) {
				File f = files[i];
				searchDirectory(f, rootItem);
			}
		} else if (file.getName().endsWith(".rsb")) {
			TreeItem fileItem = new TreeItem(rootItem, 0);
			fileItem.setText(file.getName() + " - "
					+ file.getPath().substring(ROOT_PATH.length() + 1));
			fileItem.setImage(fileImage);
			fileItem.setData("Type", "File");
			fileItem.setData("Path", file.getPath());
		}
	}

	public void refrashMethodTable(String filePath,String selectMethodName) {
		fileMethodList.removeAll();
		if (filePath == null) {
			return;
		}
		try {
			int selectIdx=-1;
			File file = new File(filePath);
			// fileMethodList.setData("Path", file.getPath());
			SAXBuilder builder = new SAXBuilder();
			Document document = builder.build(file);
			Element root = document.getRootElement();
			if ("ServiceBuilder".equals(root.getName())) {
				List<Element> methods = root.getChildren();
				for (int i = 0; i < methods.size(); i++) {
					Element method = methods.get(i);
					TableItem item = new TableItem(fileMethodList, SWT.NONE);
					item.setText(new String[] { method.getAttributeValue("id"),
							method.getAttributeValue("name"),
							// method.getAttributeValue("type"),
							method.getAttributeValue("comment") });
					item.setData("Path", file.getPath());
					if(selectMethodName!=null&&selectMethodName.equals(method.getAttributeValue("name"))){
						selectIdx=i;
					}
				}
			}
			if(selectIdx>=0){
				fileMethodList.setSelection(selectIdx);
			}
		} catch (Exception e) {
		}
	}

	class xmlFilter implements FileFilter {
		public xmlFilter() {
		}

		public boolean accept(File file) {
			// System.out.println("name:"+file.getName());
			if (file.isDirectory()) {
				return true;
			}
			if (file.getName().endsWith(".java")) {
				return false;
			}
			if (file.getName().endsWith(".rsb")
					|| file.getName().endsWith(".RSB")) {
				return true;
			}
			return false;
		}
	}

	@Override
	protected void checkSubclass() {
		// Disable the check that prevents subclassing of SWT components
	}
}
